<?php

namespace App\Http\Controllers\background;

use App\Http\Controllers\Controller;
use App\Models\Admin\InterfaceConfiguration;
use App\Models\Mysql\{CycleOrder,
    XnGoodsCarmyType,
    XnMerchantBill,
    XnOrder,
    XnOrderBill,
    XnOrderBillCensus,
    XnSupplierGoods,
    XnTime};
use Illuminate\Http\Request;
class OrderbillController extends Controller
{
    public function mechantOrder(Request $request){
        $params = $request -> post();
        $userName = isset($params['account']) ? $params['account'] : '';//充值账号
        $goods_id = isset($params['goodsId']) ? $params['goodsId'] : '';//商品id
        $goods_code = isset($params['goods_code']) ? $params['goods_code'] : '';//商品id
        $recharge_status = isset($params['recharge_status']) ? $params['recharge_status'] : '';//订单状态
        $start_time = $params['start_time'];//开始时间
        $end_time = $params['end_time'];//结束时间
        $Merchant_num = isset($params['order_sn']) ? $params['order_sn'] : '';//商户订单号
        $Merchant = isset($params['mecahnt_num']) ? $params['mecahnt_num'] : '';//商户号
        $types = isset($params['types']) ?  $params['types'] : 0;
        $condition = [];
        if(!empty($start_time) && !empty($end_time)){
            $condition[] = ['recharge_time','>=',$start_time];
            $condition[] = ['recharge_time','<=',$end_time];
        }
        if(!empty($Merchant)){
            $condition[] = ['merchant_number','=',$Merchant];
        }
        if(!empty($goods_id)){
            $condition[] = ['gid','=',$goods_id];

        }
        if(!empty($goods_code)){
            $condition[] = ['goods_code','=',$goods_code];

        }
        if(!empty($Merchant_num)){
            $condition[] = ['order_sn','=',$Merchant_num];
        }
        if($recharge_status != null){
            $condition[] = ['recharge_status','=',$recharge_status];
        }
        if (!empty($userName)){
            $condition[] = ['account','=',$userName];
        }
        $condition[] = ['order_type','=',$types];
        $res = XnOrder::where($condition)
            ->orderBy('id','desc')
            ->paginate(10)
            ->toArray();
        if (!$res){
            return fails('查询失败');
        }else{
            if($res['data']){
                foreach($res['data'] as $k => $v){
                    $res['data'][$k]['goods_belong'] = InterfaceConfiguration::where('id',$v['goods_belong']) -> value('title');
                }
            }
            return successly($res);
        }
    }

    public function orderbilllist(Request $request){
        $b_type = $request-> post('b_type');
        $before_atime = $request-> post('before_atime','');
        $after_atime = $request-> post('after_atime','');
        $order_no = $request-> post('order_no','');
        $order_type = $request-> post('order_type','');
        $supplier_status = $request-> post('supplier_status','');
        $mecahnt_number = $request-> post('mechant_number','');
        if(!empty($supplier_status)){
            $condition[] = ['goods_belong','=',$supplier_status];
        }
        if(!empty($order_no)){
            $condition[] = ['order_sn','=',$order_no];
        }
        if(!empty($mecahnt_number)){
            $condition[] =  ['merchant_number','=',$mecahnt_number];
        }
        if(!empty($b_type)){
            $condition[] = ['bookkeeping_type','=',$b_type];
        }
        if(!empty($before_atime) && !empty($after_atime)){
            $condition[] = ['ctime','>=',$before_atime];
            $condition[] = ['ctime','<=',$after_atime];
        }

        $condition[]= ['order_type','=',$order_type];
        $list = XnOrderBill::where($condition) -> orderBy('ctime','desc') -> paginate(10) -> toArray();
        if(!$list){
            return  fails('暂无数据');
        }
        return successly($list);
    }
    // 获取总金额
    public function getsummoney(Request $request){
            $b_type = $request-> post('b_type');
            $before_atime = $request-> post('before_atime','');
            $after_atime = $request-> post('after_atime','');
            $order_no = $request-> post('order_no','');
            $order_type = $request-> post('order_type','');
            $supplier_status = $request-> post('supplier_status','');
            $mecahnt_number = $request-> post('mecahnt_number','');
            $condition = [];
            if(!empty($supplier_status)){
                $condition[] = ['goods_belong','=',$supplier_status];
            }
            if(!empty($order_no)){
                $condition[] = ['order_num','=',$order_no];
            }
            if(!empty($mecahnt_number)){
                $condition[] =  ['mechant_number','=',$mecahnt_number];
            }
            if(!empty($b_type)){
                $condition[] = ['bookkeeping_type','=',$b_type];
            }
            if(!empty($before_atime) && !empty($after_atime)){
                $condition[] = ['ctime','>=',$before_atime];
                $condition[] = ['ctime','<=',$after_atime];
            }
            $condition[]= ['order_type','=',$order_type];
            $res['income'] = $this -> getmoney($condition,1,$b_type);
            $res['expend'] = $this -> getmoney($condition,2,$b_type);
            $res['allmoney'] = $this -> getmoney($condition,3,$b_type);
            return $res;

    }
    // 根据条件获取金额
    public function getmoney($condition,$type,$b_type){
        if($type == 1){
            if(empty($b_type)){
                $condition[] = ['bookkeeping_type','=',1];
            }else if($b_type == 2){
                return 0;
            }
            return XnOrderBill
                ::where($condition)
                -> sum('budget_money');
        }else if($type == 2){
            if(empty($b_type)){
                $condition[] = ['bookkeeping_type','=',2];
            }else if($b_type == 1){
                return 0;
            }
            return XnOrderBill
                ::where($condition)
                -> sum('budget_money');

        }else if($type == 3){
            return XnOrderBill
                ::where($condition)
                -> sum('budget_money');
        }
    }
    public function orderbilldetail(Request $request){
        $id = $request -> post('o_id');
        if(empty($id)){
            return fails('请传参数');
        }
        $res = XnOrderBill::find($id)->toArray();
        $res['goods_belong'] = InterfaceConfiguration::find($res['goods_belong']) -> title;
        if(!$res){
            return fails('暂无数据');
        }
        return successly($res);
    }

    public function rechargebill(Request $request){
        $account = $request -> post('mechant_number','');
        if(!empty($account)){
            $condition[] = ['merchant_number','=',$account];
        }
        $condition['status'] = 1;
        $start = $request -> post('starttime','');
        $end =$request -> post('endtime','');
        if (!empty($start) && !empty($end)) {
            $condition[] = ['time','>=',$start];
            $condition[] = ['time','<=',$end];
        }
        $funds_t = $request -> post('funds_t');
        $is_check = $request -> post('is_check');
        if(!empty($funds_t)){
            $condition[] = ['funds_type','=',$funds_t];
        }
        if(!empty($is_check)){
            $condition[] = ['is_check','=',$is_check];
        }
        $remarks = $request -> post('remarks');
        if(!empty($remarks)){
            $condition[] = ['remarks','like','%'.$remarks.'%'];
        }
        $condition[] = ['status','=',1];
        $list = XnMerchantBill::where($condition)->orderBy('time','desc')->paginate(10) -> toArray();
        $money = XnMerchantBill::where($condition)->sum('transaction_amount');
        $list['all_money'] = $money;
        if(!$list){
            return fails('暂无数据');
        }
        return successly($list);
    }
    public function setfundstype(Request $request){
        $id = $request -> post('b_id');
        $type = $request -> post('funds_type');
        if(empty($id)){
            return fails('请传参数');
        }
        if(empty($type)){
            return fails('请传类型');
        }
        $flight = XnMerchantBill::find($id);

        $flight->funds_type = $type;

        $flight->save();
        return successly();
    }
    public function setremarks(Request $request){
        $id = $request -> post('b_id');
        $remarks = $request -> post('remarks');
        if(empty($id)){
            return fails('请传参数');
        }
        if(empty($remarks)){
            return  fails('请传备注');
        }
        $flight = XnMerchantBill::find($id);

        $flight->remarks = $remarks;

        $flight->save();
        return  successly();
    }
    public function checkbill(Request $request){
        $id = $request -> post('b_id');
        $check_man = $request -> post('check_man');
        if(empty($id)){
            return fails('请传参数');
        }
        if(empty($check_man)){
            return fails('请传操作人');
        }
        $flight = XnMerchantBill::find($id);
        $flight->check_man = $check_man;
        $flight->is_check = 1;
        $flight->save();
        return successly();
    }
    public function cutbill(Request $request){
        $account = $request -> post('mechant_number','');
        if(!empty($account)){
            $condition[] = ['merchant_number','=',$account];
        }
        $phone = $request -> post('phone','');
        if(!empty($account)){
            $condition[] = ['phone','=',$phone];
        }
        //$condition['status'] = 1;
        $start = $request -> post('starttime','');
        $end = $request -> post('endtime','');
        if (!empty($start) && !empty($end)) {
            $condition[] = ['time','>=',$start];
            $condition[] = ['time','<=',$end];
        }
        $condition[] = ['status','=',4];
        $list = XnMerchantBill::where($condition)->orderBy('time','desc')->paginate(10) -> toArray();
        $money = XnMerchantBill::where($condition)->sum('transaction_amount');
        $list['all_money'] = $money;
        if(!$list){
            return  fails('暂无数据');
        }
        return  successly($list);
    }


    public function accountbill(Request $request){
        $goods_id = $request -> post('goods_id','');
        $types = $request -> post('types','');
        $start_time = $request -> post('start_time','');
        $end_time = $request -> post('end_time','');
        $bookkeeping_type = $request -> post('bookkeeping_type','');
        $business_type = $request -> post('business_type','');
        $Supplier_status = $request -> post('Supplier_status','');
        $order_no = $request -> post('order_no','');
        $recharge_status = $request -> post('recharge_status','');
        // 接收时间条件
        if(!empty($start_time) && !empty($end_time)){
            $condition[] = ['ctime','>=',$start_time];
            $condition[] = ['ctime','<=',$end_time];
        }
        if(!empty($goods_id)){
            $condition[] = ['goods_id','=',$goods_id];
        }
        // 接收记账类型条件
        if(!empty($bookkeeping_type)){
            $condition[] = ['bookkeeping_type','=',$bookkeeping_type];
        }
        // 接收业务类型条件
        if(!empty($business_type)){
            $condition[] = ['business_type','=',$business_type];
        }
        // 接收商品归属
        if(!empty($Supplier_status)){
            $condition[] = ['goods_belong','=',$Supplier_status];
        }
        // 接收业务订单号
        if(!empty($order_no)){
            $condition[] = ['order_sn','=',$order_no];
        }
        // 接收充值状态
        if(!empty($recharge_status)){
            $condition[] = ['recharge_status','=',$recharge_status];
        }
        $condition[] = ['order_type','=',$types];
        $res = XnOrderBill::where($condition)
            -> orderBy('id','desc')
            -> paginate(10)
            ->toArray();
        if($res['data']){
            foreach($res['data'] as $k => $v){
                $res['data'][$k]['goods_belong'] = InterfaceConfiguration::where('id',$v['goods_belong']) -> value('title');
            }
        }
        if($bookkeeping_type == 1){
            $res['income'] = $this -> getallsum($condition);
            $res['expend'] = 0;
        }else if($bookkeeping_type == 2){
            $res['income'] = 0;
            $res['expend'] = $this -> getallsum($condition);
        }else{
            $res['income'] = $this -> getallsum($condition,2);
            $res['expend'] =  $this -> getallsum($condition,3);
        }
        return successly($res);
    }

    public function getallsum($condition,$type = 1){
        if($type == 2 ){
            $condition[] = ['bookkeeping_type','=',1];
        }else if($type == 3){
            $condition[] = ['bookkeeping_type','=',2];
        }
        $money = XnOrderBill::where($condition)
            -> sum('budget_money');
        $count =XnOrderBill::where($condition)
            -> count();
        return ['money'=>$money,'count'=>$count];
    }

    public function gettime(Request $request){
        $type = $request -> post('type');
        if(empty($type)){
            return  fails('请传参');
        }
        $years = XnTime::where('type','=',$type)
            -> distinct()
            -> latest('year')
            -> select('year')
            -> get()
            -> toArray();
        foreach($years as $k=>$v){
            $years[$k]['month'] = XnTime::where('type','=',$type)
                -> where('year','=',$v['year'])
                -> latest('month')
                -> pluck('month');
        }
        return successly($years);
    }
    public function monthcensus(Request $request){
        $year = $request -> post('year');
        $type = $request -> post('types');
        $condition[] = ['type','=',$type];
        $condition[] = ['year','=',$year];
        $data = XnOrderBillCensus::where($condition)
            ->groupBy('month')
            ->selectRaw('month,SUM(income_money) as i_money,SUM(income_count) as i_count,SUM(out_monoey) as o_money,SUM(out_count) as o_count')
            ->latest('month')
            ->get()
            ->toArray();
        $infos = [];
        foreach ($data as $k => $v) {
            $infos[$k]['month'] = $v['month'];
            $infos[$k]['income_money'] = $v['i_money'];
            $infos[$k]['income_pen'] = $v['i_count'];
            $infos[$k]['pay_money'] = $v['o_money'];
            $infos[$k]['pay_pen'] = $v['o_count'];
            $monthmoney = $this->getmonthmonry($year, $v['month'], $type);
            $infos[$k]['initial_balance'] = $monthmoney['b_money'];
            $infos[$k]['ending_balance'] = $monthmoney['e_money'];
        }
        return successly($infos);
    }

    public function getmonthmonry($year,$month,$type){
        $where[] = ['year','=',$year];
        $where[] = ['month','=',$month];
        $where[] = ['type','=',$type];
        $b_money = XnOrderBillCensus::where($where)
            ->latest('day')
            ->limit(1)
            ->value('begin_money');
        $e_money = XnOrderBillCensus::where($where)
            ->oldest('day')
            ->limit(1)
            ->value('end_money');
        return ['b_money'=>$b_money,'e_money'=>$e_money];
    }

    public function daycensus(Request $request){
        $day = $request -> post('day','');
        if(empty($day)){
            return fails('请传参数');
        }
        $type = $request -> post('type','');
        if(empty($day)){
            return fails('请传参数');
        }
        $ctime = explode('-',$day);
        $where[] = ['year','=',$ctime[0]];
        $where[] = ['month','=',$ctime[1]];
        $where[] = ['type','=',$type];
        $res = XnOrderBillCensus::where($where)
            ->latest('day')
            ->get()
            ->toArray();
        return successly($res);
    }

    public function goodsName(Request $request){
            $goodsId = $request -> post('goodsId','');
            if(empty($goodsId)){
                return fails('请传参数');
            }
            $goodsName = XnSupplierGoods::find($goodsId);
            return successly($goodsName);
    }

    public function goodsVital(Request $request){
        $params = $request -> post();
        $userName = isset($params['account']) ? $params['account'] : '';//充值账号
        $goods_id = isset($params['goodsId']) ? $params['goodsId'] : '';//商品id
        $goods_code = isset($params['goods_code']) ? $params['goods_code'] : '';//商品id
        $recharge_status = isset($params['recharge_status']) ? $params['recharge_status'] : '';//订单状态
        $start_time = $params['start_time'];//开始时间
        $end_time = $params['end_time'];//结束时间
        $Merchant_num = isset($params['order_sn']) ? $params['order_sn'] : '';//商户订单号
        $Merchant = isset($params['mecahnt_num']) ? $params['mecahnt_num'] : '';//商户号
        $types = isset($params['types']) ?  $params['types'] : 0;
        $condition = [];
        if(!empty($start_time) && !empty($end_time)){
            $condition[] = ['recharge_time','>=',$start_time];
            $condition[] = ['recharge_time','<=',$end_time];
        }
        if(!empty($Merchant)){
            $condition[] = ['merchant_number','=',$Merchant];
        }
        if(!empty($goods_id)){
            $condition[] = ['gid','=',$goods_id];

        }
        if(!empty($goods_code)){
            $condition[] = ['goods_code','=',$goods_code];

        }
        if(!empty($Merchant_num)){
            $condition[] = ['order_sn','=',$Merchant_num];
        }
        if (!empty($userName)){
            $condition[] = ['account','=',$userName];
        }
        $condition[] = ['recharge_status','=',1];
        $condition[] = ['order_type','=',$types];
        $count = XnOrder::where($condition)
            ->selectRaw('count(id) as num,goods_belong')
            ->groupBy('goods_belong')
            ->get()
            ->toArray();

        foreach($count as $k => $v){
            $count[$k]['goods_belong'] = InterfaceConfiguration::find($v['goods_belong'])-> title;
        }
        $counts = array_sum(array_column($count, 'num'));
        $res = [];
        if($counts>0){
            $res['success_count'] = $counts;
        }else{
            $res['success_count'] ='';
        }
        if(!empty($count)){
            $res['success_name'] = $count;
        }else{
            $res['success_name'] = '';
        }

        return successly($res);
    }

    // 循环充统计
    public function cycleVital(Request $request){
        $params = $request -> post();
        $userName = isset($params['account']) ? $params['account'] : '';//充值账号
        $goods_id = isset($params['goodsId']) ? $params['goodsId'] : '';//商品id
        $goods_code = isset($params['goods_code']) ? $params['goods_code'] : '';//商品id
        $recharge_status = isset($params['recharge_status']) ? $params['recharge_status'] : '';//订单状态
        $start_time = $params['start_time'];//开始时间
        $end_time = $params['end_time'];//结束时间
        $Merchant_num = isset($params['order_sn']) ? $params['order_sn'] : '';//商户订单号
        $Merchant = isset($params['mecahnt_num']) ? $params['mecahnt_num'] : '';//商户号
        $types = isset($params['types']) ?  $params['types'] : 0;
        $condition = [];
        if(!empty($start_time) && !empty($end_time)){
            $condition[] = ['recharge_time','>=',$start_time];
            $condition[] = ['recharge_time','<=',$end_time];
        }
        if(!empty($Merchant)){
            $condition[] = ['merchant_number','=',$Merchant];
        }
        if(!empty($goods_id)){
            $condition[] = ['gid','=',$goods_id];

        }
        if(!empty($goods_code)){
            $condition[] = ['goods_code','=',$goods_code];

        }
        if(!empty($Merchant_num)){
            $condition[] = ['order_sn','=',$Merchant_num];
        }
        if (!empty($userName)){
            $condition[] = ['account','=',$userName];
        }
        $condition[] = ['recharge_status','=',1];
        $condition[] = ['order_type','=',$types];
        $condition[] = ['goods_belong','=',2];
        $order_sn_info = XnOrder::where($condition)
            ->pluck('order_sn');
        $cy_condition[] = ['state','=',1];
        if(!empty($start_time) && !empty($end_time)){
            $cy_condition[] = ['create_time','>=',$start_time];
            $cy_condition[] = ['create_time','<=',$end_time];
        }
        $count = CycleOrder::whereIn('order_no',$order_sn_info)
            ->where($cy_condition)
            ->selectRaw('count("*") as num,supplier_status')
            ->groupBy('supplier_status')
            ->get()
            ->toArray();
        foreach($count as $k => $v){
            $title = InterfaceConfiguration::where('id',$v['supplier_status']) -> value('title');
            if(empty($title)){
                $title = XnGoodsCarmyType::where('type',$v['supplier_status']) -> value('name');
            }
            $count[$k]['supplier_status'] = $title;
        }
        $counts = array_sum(array_column($count, 'num'));
        $res = [];
        if($counts>0){
            $res['success_count'] = $counts;
        }else{
            $res['success_count'] ='';
        }
        if(!empty($count)){
            $res['success_name'] = $count;
        }else{
            $res['success_name'] = '';
        }
        return successly($res);
    }
}
